package com.example.merchantdemo.paymentstart.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.merchantdemo.constants.MerchantInfoConstant;
import com.example.merchantdemo.constants.SecretKeyConstant;
import com.example.merchantdemo.paymentstart.dto.*;
import com.example.merchantdemo.util.HttpClientUtil;
import com.example.merchantdemo.util.SignatureGenerateHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Collections;
import java.util.Objects;

@RestController
@RequestMapping("/payment")
public class PaymentStartController {

    private static final Logger logger = LoggerFactory.getLogger(PaymentStartController.class);

    /**
     * 平台基础调用url
     */
    public static final String hostAddress = "https://pay.6du.io";

    /**
     * 发起支付
     *
     * @param startToPayReq
     */
    @PostMapping("/startToPay")
    public PlatformResponse<StartToPayResp> startToPay(@RequestBody StartToPayReq startToPayReq) {

        StartToPayRequest request = new StartToPayRequest();
        BeanUtils.copyProperties(startToPayReq, request);

        // 商户app_id
        request.setMerchantId(MerchantInfoConstant.MERCHANT_APP_ID);
        request.setSubject("这里填商品标题");
        // 填写商户方订单号(不可重复)
        request.setMerchantOrderCode(String.valueOf(System.currentTimeMillis()));

        // 签名
        String sign = SignatureGenerateHelper.generateSign(SecretKeyConstant.MERCHANT_PRIVATE_KEY, request);
        request.setMerchantSign(sign);

        //向支付平台发起创建支付订单
        String result =
                HttpClientUtil.sendHttpPostJson(hostAddress + "/pay/v3.0/createPrePaymentBill",
                        Collections.EMPTY_MAP,
                        Collections.EMPTY_MAP, JSONObject.toJSONString(request));

        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!Objects.equals(200, jsonObject.getInteger("code"))) {
            throw new RuntimeException(jsonObject.getString("message"));
        }
        JSONObject body = jsonObject.getJSONObject("data");
        CreatePrePaymentBillResp resp = JSONObject.parseObject(JSONObject.toJSONString(body),
                CreatePrePaymentBillResp.class);

        // 对返回参数验签
        Boolean verifyResult = SignatureGenerateHelper.verifyRSASign(SecretKeyConstant.PLATFORM_PUBLIC_KEY,
                JSONObject.toJSONString(body),
                resp.getMerchantSign());

        if (!verifyResult) {
            throw new RuntimeException("验签失败");
        }

        // 组装给前端的返回参数，并签名
        StartToPayResp payResp = new StartToPayResp();
        BeanUtils.copyProperties(resp, payResp);

        InitToPayment initToPayment = new InitToPayment();
        initToPayment.setBillCode(resp.getBillCode());
        initToPayment.setMerchantId(MerchantInfoConstant.MERCHANT_APP_ID);
        initToPayment.setRequestTimestamp(System.currentTimeMillis());
        initToPayment.setMerchantSign(SignatureGenerateHelper.generateSign(SecretKeyConstant.MERCHANT_PRIVATE_KEY,
                initToPayment));

        payResp.setInitToPayment(initToPayment);

        logger.info(JSONObject.toJSONString(payResp));

        PlatformResponse response = new PlatformResponse();
        response.setCode(200);
        response.setMessage("调用成功");
        response.setData(payResp);

        return response;

    }

    /**
     * 此接口提供给前端，供前端轮训查询订单状态
     */
    @PostMapping("queryBillStatus")
    public PlatformResponse<QueryBillStatusResp> queryBillStatus(@Valid @RequestBody QueryBillStatusReq req) {

        // 在接收到平台 支付到账推送成功 后，需要把商户订单状态改为成功。
        // 此时前端需要轮询此接口，获取订单状态。订单成功则在订单页告知用户成功，订单失败也同样告知用户

        // 这里查询商户订单状态，返回给前端

        QueryBillStatusResp resp = new QueryBillStatusResp();
        resp.setOrderStatus(1); // 查询到的订单状态

        PlatformResponse response = new PlatformResponse();
        response.setCode(200);
        response.setMessage("调用成功");
        response.setData(resp);

        return response;
    }

    /**
     * 商户端取消买币订单
     *
     * @param req
     * @return
     */
    @PostMapping("/cancelTakeOrder")
    public PlatformResponse cancelTakeOrder(@Valid @RequestBody CancelTakeOrderReq req) {

        CancelTakeOrderRequest request = new CancelTakeOrderRequest();
        request.setMerchantId(MerchantInfoConstant.MERCHANT_APP_ID);
        request.setMerchantOrderCode(req.getMerchantOrderCode());
        request.setMerchantSign(SignatureGenerateHelper.generateSign(SecretKeyConstant.MERCHANT_PRIVATE_KEY, request));

        //向支付平台发起取消订单
        String result =
                HttpClientUtil.sendHttpPostJson(hostAddress + "/pay/v3.0/merchantCancelTakeOrder",
                        Collections.EMPTY_MAP,
                        Collections.EMPTY_MAP, JSONObject.toJSONString(request));

        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!Objects.equals(200, jsonObject.getInteger("code"))) {
            throw new RuntimeException(jsonObject.getString("message"));
        }

        PlatformResponse response = new PlatformResponse();
        response.setCode(jsonObject.getInteger("code"));
        response.setMessage(jsonObject.getString("message"));
        response.setData(new JSONObject());

        return response;
    }

    /**
     * 跳转app支付
     *
     * @return
     */
    @PostMapping("/skipToAppPayment")
    public PlatformResponse skipToAppPayment(@Valid @RequestBody SkipToAppPaymentReq req) {

        SkipToAppPaymentRequest request = new SkipToAppPaymentRequest();
        BeanUtils.copyProperties(req,request);

        // 商户生成订单，并将订单号传给支付平台
        request.setMerchantOrderCode(""+System.currentTimeMillis());
        request.setCurrencyName("CNY");
        request.setMerchantId(MerchantInfoConstant.MERCHANT_APP_ID);
        request.setSubject("订单标题");
        request.setMerchantSign(SignatureGenerateHelper.generateSign(SecretKeyConstant.MERCHANT_PRIVATE_KEY, request));

        String result =
                HttpClientUtil.sendHttpPostJson(hostAddress + "/pay/v3.0/skipToAppPayment",
                        Collections.EMPTY_MAP, Collections.EMPTY_MAP, JSONObject.toJSONString(request));

        JSONObject jsonObject = JSONObject.parseObject(result);
        if (!Objects.equals(200, jsonObject.getInteger("code"))) {
            throw new RuntimeException(jsonObject.getString("message"));
        }
        String billCode = jsonObject.getJSONObject("data").getString("billCode");
        SkipToAppPaymentResp resp =new SkipToAppPaymentResp();
        BeanUtils.copyProperties(request,resp);
        resp.setBillCode(billCode);
        resp.setMerchantSign(SignatureGenerateHelper.generateSign(SecretKeyConstant.MERCHANT_PRIVATE_KEY, resp));

        PlatformResponse response = new PlatformResponse();
        response.setCode(200);
        response.setMessage("调用成功");
        response.setData(resp);

        return response;
    }
}
